package com.example.testplatform.service.impl;

// 移除未使用的导入语句
import com.example.testplatform.common.LogUtils;
import com.example.testplatform.entity.TestApplication;
import com.example.testplatform.mapper.TestApplicationMapper;
import com.example.testplatform.service.TestApplicationService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class TestApplicationServiceImpl implements TestApplicationService {
    
    private static final Logger logger = LogUtils.getLogger(TestApplicationServiceImpl.class);
    
    @Autowired
    private TestApplicationMapper testApplicationMapper;
    
    @Override
    public Map<String, Object> getApplicationList(Integer page, Integer pageSize, Map<String, Object> params) {
        long startTime = System.currentTimeMillis();
        
        // 保存原始参数的final版本用于日志记录
        final Integer originalPage = page;
        final Integer originalPageSize = pageSize;
        final Map<String, Object> originalParams = params;
        
        try {
            LogUtils.debug(logger, () -> "【测试申请管理】开始分页查询测试申请单列表: 页码=" + originalPage + ", 每页数量=" + originalPageSize + ", 查询参数=" + originalParams);
            
            // 参数校验
            if (page == null || page <= 0) {
                page = 1;
                LogUtils.warn(logger, "【测试申请管理】分页参数校验: 页码无效，已默认设置为1");
            }
            if (pageSize == null || pageSize <= 0 || pageSize > 100) {
                pageSize = 10;
                LogUtils.warn(logger, "【测试申请管理】分页参数校验: 每页数量无效，已默认设置为10");
            }
            if (params == null) {
                params = new HashMap<>();
                LogUtils.warn(logger, "【测试申请管理】分页参数校验: 查询参数为空，已使用空Map替代");
            }
            
            // 创建处理后参数的final版本
            final Integer finalPage = page;
            final Integer finalPageSize = pageSize;
            final Map<String, Object> finalParams = params;
            
            int offset = (page - 1) * pageSize;
            
            // 提取查询参数
            Long productId = params.get("productId") != null ? Long.valueOf(params.get("productId").toString()) : null;
            Integer status = params.get("status") != null ? Integer.valueOf(params.get("status").toString()) : null;
            Long applicantId = params.get("applicantId") != null ? Long.valueOf(params.get("applicantId").toString()) : null;
            Long testerId = params.get("testerId") != null ? Long.valueOf(params.get("testerId").toString()) : null;
            String startTimeStr = params.get("startTime") != null ? params.get("startTime").toString() : null;
            String endTimeStr = params.get("endTime") != null ? params.get("endTime").toString() : null;
            
            LogUtils.debug(logger, () -> "【测试申请管理】提取查询参数完成: productId=" + productId + ", status=" + status + ", applicantId=" + applicantId + ", testerId=" + testerId + ", startTime=" + startTimeStr + ", endTime=" + endTimeStr);
            
            List<Map<String, Object>> applications = testApplicationMapper.findAll(
                    offset, pageSize, productId, status, applicantId, testerId, startTimeStr, endTimeStr);
            Integer total = testApplicationMapper.count(
                    productId, status, applicantId, testerId, startTimeStr, endTimeStr);
            
            // 处理状态中文显示
            for (Map<String, Object> application : applications) {
                if (application.containsKey("status")) {
                    Integer statusValue = (Integer) application.get("status");
                    application.put("statusName", getStatusName(statusValue));
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", applications);
            result.put("total", total);
            
            LogUtils.info(logger, () -> "【测试申请管理】分页查询测试申请单列表成功: 页码=" + finalPage + ", 每页数量=" + finalPageSize + ", 总记录数=" + total + ", 当前页记录数=" + applications.size());
            LogUtils.logPerformance(logger, "getApplicationList", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】分页查询测试申请单列表异常: 页码=" + originalPage + ", 每页数量=" + originalPageSize + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Override
    public TestApplication getApplicationById(Long id) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.debug(logger, () -> "【测试申请管理】开始根据ID获取测试申请单: " + id);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】根据ID获取测试申请单失败: ID无效");
                return null;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            LogUtils.debug(logger, () -> "【测试申请管理】根据ID " + id + " 获取测试申请单结果: " + (application != null ? "找到申请单" : "未找到申请单"));
            LogUtils.logPerformance(logger, "getApplicationById", startTime, System.currentTimeMillis());
            return application;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】根据ID获取测试申请单异常: " + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createApplication(TestApplication application) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_CREATE_ATTEMPT", "system", "【测试申请管理】创建测试申请单尝试: 产品ID=" + (application != null ? application.getProductId() : "null"));
            LogUtils.debug(logger, () -> "【测试申请管理】开始创建测试申请单");
            
            // 参数校验
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】创建测试申请单失败: 申请单对象为空");
                return false;
            }
            if (application.getProductId() == null || application.getProductId() <= 0) {
                LogUtils.warn(logger, "【测试申请管理】创建测试申请单失败: 产品ID无效");
                return false;
            }
            
            // 默认状态为待提交
            if (application.getStatus() == null) {
                application.setStatus(0);
                LogUtils.debug(logger, () -> "【测试申请管理】设置默认状态为待提交(0)");
            }
            
            boolean result = testApplicationMapper.insert(application) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】创建测试申请单成功: 申请单ID=" + application.getId() + ", 产品ID=" + application.getProductId() + ", 状态=" + getStatusName(application.getStatus()));
                LogUtils.logBusiness(logger, "TEST_APPLICATION_CREATE_SUCCESS", "system", "【测试申请管理】创建测试申请单成功: 申请单ID=" + application.getId() + ", 产品ID=" + application.getProductId());
            } else {
                LogUtils.warn(logger, "【测试申请管理】创建测试申请单失败: 产品ID={}", application.getProductId());
            }
            
            LogUtils.logPerformance(logger, "createApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】创建测试申请单异常: 产品ID=" + (application != null ? application.getProductId() : "null") + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateApplication(TestApplication application) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_UPDATE_ATTEMPT", "system", "【测试申请管理】更新测试申请单尝试: 申请单ID=" + (application != null ? application.getId() : "null"));
            LogUtils.debug(logger, () -> "【测试申请管理】开始更新测试申请单");
            
            // 参数校验
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】更新测试申请单失败: 申请单对象为空");
                return false;
            }
            if (application.getId() == null || application.getId() <= 0) {
                LogUtils.warn(logger, "【测试申请管理】更新测试申请单失败: 申请单ID无效");
                return false;
            }
            
            TestApplication existing = testApplicationMapper.findById(application.getId());
            if (existing == null) {
                LogUtils.warn(logger, "【测试申请管理】更新测试申请单失败: 申请单ID={} 不存在", application.getId());
                return false;
            }
            
            // 已提交的申请单不允许修改基本信息
            if (existing.getStatus() > 0 && existing.getStatus() < 6) {
                LogUtils.warn(logger, "【测试申请管理】更新测试申请单失败: 申请单ID={} 已提交，状态为 {}，不允许修改", application.getId(), getStatusName(existing.getStatus()));
                return false;
            }
            
            // 记录变更信息
            LogUtils.debug(logger, () -> "【测试申请管理】申请单更新前信息: ID=" + existing.getId() + ", 状态=" + getStatusName(existing.getStatus()) + ", 产品ID=" + existing.getProductId());
            
            boolean result = testApplicationMapper.update(application) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】更新测试申请单成功: 申请单ID=" + application.getId() + ", 更新后状态=" + getStatusName(application.getStatus()));
                LogUtils.logBusiness(logger, "TEST_APPLICATION_UPDATE_SUCCESS", "system", "【测试申请管理】更新测试申请单成功: 申请单ID=" + application.getId());
            } else {
                LogUtils.warn(logger, "【测试申请管理】更新测试申请单失败: 申请单ID={}", application.getId());
            }
            
            LogUtils.logPerformance(logger, "updateApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】更新测试申请单异常: 申请单ID=" + (application != null ? application.getId() : "null") + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteApplication(Long id) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_DELETE_ATTEMPT", "system", "【测试申请管理】删除测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始删除测试申请单: 申请单ID=" + id);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】删除测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】删除测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            // 已提交的申请单不允许删除
            if (application.getStatus() > 0 && application.getStatus() < 6) {
                LogUtils.warn(logger, "【测试申请管理】删除测试申请单失败: 申请单ID={} 已提交，状态为 {}，不允许删除", id, getStatusName(application.getStatus()));
                return false;
            }
            
            boolean result = testApplicationMapper.delete(id) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】删除测试申请单成功: 申请单ID=" + id + ", 产品ID=" + application.getProductId());
                LogUtils.logBusiness(logger, "TEST_APPLICATION_DELETE_SUCCESS", "system", "【测试申请管理】删除测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】删除测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "deleteApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】删除测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean submitApplication(Long id) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_SUBMIT_ATTEMPT", "system", "【测试申请管理】提交测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始提交测试申请单: 申请单ID=" + id);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】提交测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】提交测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            if (application.getStatus() != 0) {
                LogUtils.warn(logger, "【测试申请管理】提交测试申请单失败: 申请单ID={} 当前状态为 {}，不是待提交状态", id, getStatusName(application.getStatus()));
                return false;
            }
            
            // 记录提交前状态
            LogUtils.debug(logger, () -> "【测试申请管理】提交前状态: 申请单ID=" + id + ", 当前状态=" + getStatusName(application.getStatus()));
            
            // 提交后状态变为待平台审核
            boolean result = testApplicationMapper.updateStatus(id, 1, null, null, null) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】提交测试申请单成功: 申请单ID=" + id + "，状态变更为: " + getStatusName(1));
                LogUtils.logBusiness(logger, "TEST_APPLICATION_SUBMIT_SUCCESS", "system", "【测试申请管理】提交测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】提交测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "submitApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】提交测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveApplication(Long id, String platformAuditOpinion) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_APPROVE_ATTEMPT", "system", "【测试申请管理】审批测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始审批测试申请单: 申请单ID=" + id + ", 平台审核意见=" + platformAuditOpinion);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】审批测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】审批测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            if (application.getStatus() != 1) {
                LogUtils.warn(logger, "【测试申请管理】审批测试申请单失败: 申请单ID={} 当前状态为 {}，不是待平台审核状态", id, getStatusName(application.getStatus()));
                return false;
            }
            
            // 记录审批前状态
            LogUtils.debug(logger, () -> "【测试申请管理】审批前状态: 申请单ID=" + id + ", 当前状态=" + getStatusName(application.getStatus()));
            
            // 平台审核通过后状态变为待测试负责人审批
            boolean result = testApplicationMapper.updateStatus(id, 2, platformAuditOpinion, null, null) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】审批测试申请单成功: 申请单ID=" + id + "，状态变更为: " + getStatusName(2) + ", 审核意见=" + platformAuditOpinion);
                LogUtils.logBusiness(logger, "TEST_APPLICATION_APPROVE_SUCCESS", "system", "【测试申请管理】审批测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】审批测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "approveApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】审批测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean rejectApplication(Long id, String platformAuditOpinion) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_REJECT_ATTEMPT", "system", "【测试申请管理】驳回测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始驳回测试申请单: 申请单ID=" + id + ", 驳回意见=" + platformAuditOpinion);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】驳回测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】驳回测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            if (application.getStatus() != 1) {
                LogUtils.warn(logger, "【测试申请管理】驳回测试申请单失败: 申请单ID={} 当前状态为 {}，不是待平台审核状态", id, getStatusName(application.getStatus()));
                return false;
            }
            
            // 记录驳回前状态
            LogUtils.debug(logger, () -> "【测试申请管理】驳回前状态: 申请单ID=" + id + ", 当前状态=" + getStatusName(application.getStatus()));
            
            // 平台审核拒绝后状态变为已驳回
            boolean result = testApplicationMapper.updateStatus(id, 6, platformAuditOpinion, null, null) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】驳回测试申请单成功: 申请单ID=" + id + "，状态变更为: " + getStatusName(6) + ", 驳回意见=" + platformAuditOpinion);
                LogUtils.logBusiness(logger, "TEST_APPLICATION_REJECT_SUCCESS", "system", "【测试申请管理】驳回测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】驳回测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "rejectApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】驳回测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean testManagerApprove(Long id, String testManagerAuditOpinion, String testerIds) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_MANAGER_APPROVE_ATTEMPT", "system", "【测试申请管理】测试负责人审批测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始测试负责人审批测试申请单: 申请单ID=" + id + ", 测试负责人意见=" + testManagerAuditOpinion + ", 测试人员ID=" + testerIds);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】测试负责人审批测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】测试负责人审批测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            if (application.getStatus() != 2) {
                LogUtils.warn(logger, "【测试申请管理】测试负责人审批测试申请单失败: 申请单ID={} 当前状态为 {}，不是待测试负责人审批状态", id, getStatusName(application.getStatus()));
                return false;
            }
            
            // 记录审批前状态
            LogUtils.debug(logger, () -> "【测试申请管理】测试负责人审批前状态: 申请单ID=" + id + ", 当前状态=" + getStatusName(application.getStatus()));
            
            // 测试负责人审批通过后状态变为待测试
            boolean result = testApplicationMapper.updateStatus(id, 3, null, testManagerAuditOpinion, testerIds) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】测试负责人审批测试申请单成功: 申请单ID=" + id + "，状态变更为: " + getStatusName(3) + ", 审批意见=" + testManagerAuditOpinion + ", 测试人员ID=" + testerIds);
                LogUtils.logBusiness(logger, "TEST_APPLICATION_MANAGER_APPROVE_SUCCESS", "system", "【测试申请管理】测试负责人审批测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】测试负责人审批测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "testManagerApprove", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】测试负责人审批测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean testManagerReject(Long id, String testManagerAuditOpinion) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_MANAGER_REJECT_ATTEMPT", "system", "【测试申请管理】测试负责人拒绝测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始测试负责人拒绝测试申请单: 申请单ID=" + id + ", 拒绝意见=" + testManagerAuditOpinion);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】测试负责人拒绝测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】测试负责人拒绝测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            if (application.getStatus() != 2) {
                LogUtils.warn(logger, "【测试申请管理】测试负责人拒绝测试申请单失败: 申请单ID={} 当前状态为 {}，不是待测试负责人审批状态", id, getStatusName(application.getStatus()));
                return false;
            }
            
            // 记录拒绝前状态
            LogUtils.debug(logger, () -> "【测试申请管理】测试负责人拒绝前状态: 申请单ID=" + id + ", 当前状态=" + getStatusName(application.getStatus()));
            
            // 测试负责人审批拒绝后状态变为已驳回
            boolean result = testApplicationMapper.updateStatus(id, 6, null, testManagerAuditOpinion, null) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】测试负责人拒绝测试申请单成功: 申请单ID=" + id + "，状态变更为: " + getStatusName(6) + ", 拒绝意见=" + testManagerAuditOpinion);
                LogUtils.logBusiness(logger, "TEST_APPLICATION_MANAGER_REJECT_SUCCESS", "system", "【测试申请管理】测试负责人拒绝测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】测试负责人拒绝测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "testManagerReject", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】测试负责人拒绝测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean cancelApplication(Long id, String reason) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.logBusiness(logger, "TEST_APPLICATION_CANCEL_ATTEMPT", "system", "【测试申请管理】取消测试申请单尝试: 申请单ID=" + id);
            LogUtils.debug(logger, () -> "【测试申请管理】开始取消测试申请单: 申请单ID=" + id + ", 取消原因=" + reason);
            
            // 参数校验
            if (id == null || id <= 0) {
                LogUtils.warn(logger, "【测试申请管理】取消测试申请单失败: ID无效");
                return false;
            }
            
            TestApplication application = testApplicationMapper.findById(id);
            if (application == null) {
                LogUtils.warn(logger, "【测试申请管理】取消测试申请单失败: 申请单ID={} 不存在", id);
                return false;
            }
            
            if (application.getStatus() >= 4 || application.getStatus() == 6) {
                LogUtils.warn(logger, "【测试申请管理】取消测试申请单失败: 申请单ID={} 当前状态为 {}，不允许取消", id, getStatusName(application.getStatus()));
                return false;
            }
            
            // 记录取消前状态
            LogUtils.debug(logger, () -> "【测试申请管理】取消前状态: 申请单ID=" + id + ", 当前状态=" + getStatusName(application.getStatus()));
            
            // 取消后状态变为已撤销
            String platformAuditOpinion = StringUtils.hasText(reason) ? reason : "申请人主动取消";
            boolean result = testApplicationMapper.updateStatus(id, 7, platformAuditOpinion, null, null) > 0;
            
            if (result) {
                LogUtils.info(logger, () -> "【测试申请管理】取消测试申请单成功: 申请单ID=" + id + "，状态变更为: " + getStatusName(7) + ", 取消原因=" + platformAuditOpinion);
                LogUtils.logBusiness(logger, "TEST_APPLICATION_CANCEL_SUCCESS", "system", "【测试申请管理】取消测试申请单成功: 申请单ID=" + id);
            } else {
                LogUtils.warn(logger, "【测试申请管理】取消测试申请单失败: 申请单ID={}", id);
            }
            
            LogUtils.logPerformance(logger, "cancelApplication", startTime, System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】取消测试申请单异常: 申请单ID=" + id + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    @Override
    public List<Map<String, Object>> getApplicationHistory(Long applicationId) {
        long startTime = System.currentTimeMillis();
        try {
            LogUtils.debug(logger, () -> "【测试申请管理】开始获取测试申请单历史记录: 申请单ID=" + applicationId);
            
            // 参数校验
            if (applicationId == null || applicationId <= 0) {
                LogUtils.warn(logger, "【测试申请管理】获取测试申请单历史记录失败: 申请单ID无效");
                return new ArrayList<>();
            }
            
            List<Map<String, Object>> history = testApplicationMapper.getHistory(applicationId);
            LogUtils.info(logger, () -> "【测试申请管理】获取测试申请单历史记录成功: 申请单ID=" + applicationId + "，历史记录数量=" + history.size());
            LogUtils.logPerformance(logger, "getApplicationHistory", startTime, System.currentTimeMillis());
            return history;
        } catch (Exception e) {
            LogUtils.error(logger, "【测试申请管理】获取测试申请单历史记录异常: 申请单ID=" + applicationId + ", 错误: " + LogUtils.formatException(e));
            throw e;
        }
    }
    
    // 辅助方法：获取状态中文名称
    private String getStatusName(Integer status) {
        switch (status) {
            case 0: return "待提交";
            case 1: return "待平台审核";
            case 2: return "待测试负责人审批";
            case 3: return "待测试";
            case 4: return "测试中";
            case 5: return "测试完成";
            case 6: return "已驳回";
            case 7: return "已撤销";
            default: return "未知";
        }
    }
}